<?php
/**
 * 工作部分
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-06-14
 * @author chenyan
 */

class workModel extends model
{
	/**************************************************************************
	 * 1 工作部分返回数据结构
	 *  work_id						int			工作ID
	 *  user_id						int			创建用户ID
	 *  work_group_id				int			所属工作分组ID
	 *  mktime						int			创建时间
	 *  end_time					int			截至时间
	 *  next_remind_time			int			下次提醒时间
	 *  remind_type					int			0：不提醒	1：提醒一次	2：周期提醒
	 *  remind_cycle_time			int			提醒周期，当且仅当：remind_type = 2时有效
	 *  subject						string		工作标题
	 *  message						string		工作内容
	 *  state						int			当前状态，0：进行中	1：已完成	2：已关闭	3：已取消
	 *  finish_percent				int			完成比例
	 *  mk_user_id					int			分配对象ID
	 *  mk_username					string		分配对象姓名
	 * 
	 * 
	 * 2工作组部分数据结构
	 * work_group_id				int			工作组ID
	 * group_id						int 		群组ID
	 * mktime						int			创建时间
	 * item_count					int			所有工作数量
	 * finish_count					int			完成数
	 * subject						string		工作组名称
	 **************************************************************************/
	
	
	/****************************work 部分*********************************/
	/**
	 * 添加工作
	 * @param int $user_id				创建用户ID
	 * @param int $work_group_id		所属工作分组ID
	 * @param int $end_time				截至时间
	 * @param int $next_remind_time		下次提醒时间
	 * @param int $remain_type			0：不提醒	1：提醒一次	2：周期提醒
	 * @param int $remind_cycle_time	提醒周期,当且仅当：remind_type = 2时有效
	 * @param string $subject			工作标题
	 * @param string $message			工作内容
	 * @param int $mk_user_id			分配对象ID
	 * @param string $mk_username		分配对象姓名
	 * 
	 * @return int 新插入记录ID
	 */
	public function add($user_id, $end_time, $subject, $message, $mk_user_id, $mk_username){
		$data = array('user_id' => $user_id,'end_date' => $end_time,
					'subject' => $subject,
					'message' => $message,'mktime'=>time(),'state' => 0,'finish_percent'=>0,
					'mk_user_id'=>$mk_user_id,'mk_username'=>$mk_username);
		$work_id = DB::insert('work', $data);
		//对应群组内容改变
		//$sql = "UPDATE ".DB::table('work_group')." SET item_count=item_count+1 WHERE work_group_id=$work_group_id";
		//$r=DB::query($sql);
		return $work_id;
	}
	
	/**
	 * 修改工作状态
	 * @param int $work_id	工作ID	
	 * @param int $state	当前状态	0：进行中	1：已完成	2：已关闭	3：已取消
	 * 
	 * @return int 1：成功 0：失败
	 */
	public function set_state($work_id,$state){
		$data = array('state' => $state);
		$condition = "work_id=$work_id";
		$row = DB::update('work',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}

	/**
	 * 修改完成比例
	 * @param int $work_id			工作ID
	 * @param int $finish_percent	完成比例
	 * 
	 * @return int 1：成功 0：失败
	 */
	public function set_finish_percent($work_id,$finish_percent){
		$data = array('finish_percent' => $finish_percent);
		$condition = "work_id=$work_id";
		$row = DB::update('work',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	
	/**
	 * 根据工作ID获取一条工作
	 * @param int $work_id			工作ID
	 */
	public function get_work($work_id){
		$row = DB::fetchOne("SELECT * FROM ".DB::table('work')." WHERE work_id = $work_id");
		if(count($row) == 0){
			return array();
		}
		return $row;
	}
	
	public function get_finished_works($user_id){
		return DB::fetchArray('SELECT * FROM '.DB::table('work').' WHERE (user_id = '.$user_id.' OR mk_user_id = '.$user_id.') AND state = 1 ORDER BY work_id DESC LIMIT 10');
	}
	
	public function get_unfinished_works($user_id){
		return DB::fetchArray('SELECT * FROM '.DB::table('work').' WHERE (user_id = '.$user_id.' OR mk_user_id = '.$user_id.') AND state = 0 ORDER BY work_id LIMIT 10');
	}
	
	/**
	 * 根据用户ID分页获取工作数量
	 * @param int $user_id		用户ID
	 */
	public function get_works_count_by_user_id($user_id){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('work')." WHERE user_id=$user_id ");
		return $row['num'];
	}
	
	/**
	 * 根据用户ID与状态分页获取工作
	 * @param int $user_id		用户ID
	 * @param int $state		当前状态	0：进行中 1：已完成 2：已关闭 3：已取消
	 * @param int $pagesize		每页大小
	 * @param int $pagenum		页号
	 * 
	 * @return 二维数组
	 */
	public function get_works_by_user_id_and_state($user_id,$state,$pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('work')." WHERE user_id=$user_id AND state=$state");
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$r = DB::fetchArray("SELECT * FROM ".DB::table('work')." WHERE user_id=$user_id AND state=$state limit $limitstart,$pagesize");
		return $r;
	}
	
	/**
	 * 根据用户ID与状态分页获取工作数量
	 * @param int $user_id		用户ID
	 * @param int $state		当前状态	0：进行中 1：已完成 2：已关闭 3：已取消
	 */
	public function get_works_count_by_user_id_and_state($user_id,$state){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('work')." WHERE user_id=$user_id AND state=$state");
		return $row['num'];
	}
	
		
	/********************************work group 部分*************************************/
	/**
	 * 增加工作组
	 * @param int $group_id		群组ID
	 * @param int $subject		工作组名
	 * 
	 * @return int 新插入记录ID
	 */
	public function add_work_group($group_id,$subject){
		$data = array('group_id' => group_id,'subject' => $subject,'mktime'=>time(),'item_count'=>0,'finish_count'=>0);
		$id = DB::insert('work_group', $data);
		return $id;
	}

	/**
	 * 获取所以工作组
	 * 
	 * @return 二维数组
	 */
	public function get_work_groups(){
		$r = DB::fetchArray("SELECT * FROM ".DB::table('work_group'));
		return $r;
	}
	/**
	 * 根据群组ID获取工作组		
	 * @param int $group_id		群组ID
	 * 
	 * @return 二维数组
	 */
	public function get_work_groups_by_group_id($group_id){
		$r = DB::fetchArray("SELECT * FROM ".DB::table('work_group')." WHERE group_id=$group_id");
		return $r;
	}

	/**
	 * 新工作发布
	 * 
	 * @param string $subject 主题
	 * @param string $message 工作内容
	 * @param mixed $relate_users 接受工作的人
	 * @param int $user_id 工作创建人
	 * @param int $type 1: 工作| 2: 待办
	public function create($subject, $message, $relate_users, $user_id){
		$relate_users = '"'.implode('","',
			explode(',', str_replace(array('"',' '), array('',''), $relate_users)) 
		).'"';
		
		$userarr = DB::fetchArray('SELECT user_id, username FROM '.DB::table('user')." WHERE username IN ({$relate_users})");
		$work_id = DB::insert('work', array(
			'user_id' => $user_id,
			'subject' => $subject,
			'message' => $message,
			'relate_user' => serialize($userarr),
		));
		$sql = 'INSERT INTO '.DB::table('todo').' (user_id, work_id, state) VALUES ';
		$datas = array();
		foreach($userarr as $i){
			$datas[] = "({$i['user_id']}, {$work_id}, 0)";
		}
		if(count($datas) > 0){
			$sql .= implode(',', $datas);
			DB::query($sql);
		}
		return $work_id;
	}
	
	public function check_users($relate_users){
		$relate_users = '"'.implode('","',
			explode(',', str_replace(array('"',' '), array('',''), $relate_users)) 
		).'"';
		$userarr = DB::fetchArray('SELECT username,user_id FROM '.DB::table('user')." WHERE username IN ({$relate_users})");
		$u = array();
		$ids = array();
		foreach($userarr as $item){
			$u[] = '"'.$item['username'].'"';
			$ids[] = $item['user_id'];
		}
		return array('usernames' =>implode(',', $u),'user_ids' =>$ids);
	}
	
	public function get_works($user_id, $type = 'finished'){
		$sql = 'SELECT * FROM '.DB::table('work')." WHERE user_id = {$user_id} AND finish_percent ";
		$sql .= $type == 'finished' ? '= 100':'<100';
		$sql .= ' LIMIT 15';
		return DB::fetchArray($sql);
	}
	
	public function get_todos_by_user_id($user_id){
		$sql = 'SELECT a.*, b.*  FROM '.DB::table('todo')." a LEFT JOIN ".DB::table('work')." b ON a.work_id = b.work_id WHERE a.user_id = {$user_id} AND state = 0 ORDER BY todo_id DESC LIMIT 15 ";
		return DB::fetchArray($sql);
	}
	
	public function get($work_id){
		return DB::fetchOne('SELECT * FROM '.DB::table('work')." WHERE work_id = {$work_id}");
	}
	
	public function get_todos_by_work_id($work_id){
		return DB::fetchArray('SELECT * FROM '.DB::table('todo')." WHERE work_id = {$work_id}");
	}
	
	public function get_todo_state($work_id, $user_id){
		$row = DB::fetchOne('SELECT state FROM '.DB::table('todo')." WHERE work_id = {$work_id} AND user_id = {$user_id}");
		if(count($row) == 0){
			return -1;
		}
		return intval($row['state']);
	}
	
	public function finish($work_id, $user_id){
		$row = DB::fetchOne('SELECT * FROM '.DB::table('work')." WHERE work_id = {$work_id}");
		if(count($row) == 0){
			return -1;
		}
		$relate_user = unserialize($row['relate_user']);
		
		$finish_count = $all_count = 0;
		$changed = false;
		foreach($relate_user as $key => $item){
			if($item['user_id'] == $user_id){
				if(!$item['f']){
					$relate_user[$key]['f'] = 1;
					$changed = true;
				}
			}
			if($relate_user[$key]['f']){
				$finish_count ++;
			}
			$all_count ++;
		}
		if($changed){
			$finish_percent = ($finish_count * 100) / $all_count;
			$finish_percent = intval($finish_percent);
			DB::update('work', array('finish_percent' => $finish_percent, 'relate_user' => serialize($relate_user)), "work_id = {$work_id}");
			DB::update('todo', array('state' => 1), "work_id = {$work_id} AND user_id = {$user_id}");
			return 1;
		}
		return 0;
	}
	*/
}
?>